package cn.itsource.service.impl;

import cn.itsource.domain.Student;
import cn.itsource.mapper.StudentMapper;
import cn.itsource.service.StudentService;
import cn.itsource.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

public class StudentServiceImpl implements StudentService {
    SqlSessionFactory sessionFactory = MyBatisUtil.getSession();
    @Override
    public List<Student> queryAll() {
        SqlSession sqlSession = sessionFactory.openSession();
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        List<Student> list = mapper.queryAll();
        if (list!=null){
            return list;
        }
        return null;
    }

    @Override
    public Student queryById(Integer id) {
        SqlSession sqlSession = sessionFactory.openSession();
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        Student stu = mapper.queryById(id);
        if (stu!=null){
            return stu;
        }
        return null;
    }

    @Override
    public boolean saveStudent(Student stu) {
        SqlSession sqlSession = null;
        try {
            sqlSession = sessionFactory.openSession();
            StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
            boolean b = mapper.saveStudent(stu);
            if (b){
                sqlSession.commit();
                return true;
            }
        }catch (Exception e){
           sqlSession.rollback();
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean updateStudent(Student stu) {
        SqlSession sqlSession = null;
        try {
            sqlSession = sessionFactory.openSession();
            StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
            boolean b = mapper.updateStudent(stu);
            if (b){
                sqlSession.commit();
                return true;
            }
        }catch (Exception e){
            sqlSession.rollback();
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean deleteStudent(Integer id) {
        SqlSession sqlSession = null;
        try {
            sqlSession = sessionFactory.openSession();
            StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
            boolean b = mapper.deleteStudent(id);
            if (b){
                sqlSession.commit();
                return true;
            }
        }catch (Exception e){
            sqlSession.rollback();
            e.printStackTrace();
        }
        return false;
    }
}
